import { fabric } from 'fabric'

export function useImageOperations(getCanvas) {
  // 上传图片
  const uploadImage = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (e) => {
      const file = e.target.files[0]
      if (file) {
        const reader = new FileReader()
        reader.onload = (event) => {
          fabric.Image.fromURL(event.target.result, (img) => {
            img.scaleToWidth(fabricCanvas.width * 0.8)
            fabricCanvas.add(img)
            fabricCanvas.renderAll()
          })
        }
        reader.readAsDataURL(file)
      }
    }
    input.click()
  }

  // 更换背景
  const changeBackground = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (e) => {
      const file = e.target.files[0]
      if (file) {
        const reader = new FileReader()
        reader.onload = (event) => {
          fabric.Image.fromURL(event.target.result, (img) => {
            img.scaleToWidth(fabricCanvas.width)
            fabricCanvas.setBackgroundImage(img, fabricCanvas.renderAll.bind(fabricCanvas))
          })
        }
        reader.readAsDataURL(file)
      }
    }
    input.click()
  }

  // 下载图片
  const downloadImage = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const dataURL = fabricCanvas.toDataURL({
      format: 'png',
      quality: 1
    })
    const link = document.createElement('a')
    link.download = 'image-editor-result.png'
    link.href = dataURL
    link.click()
  }

  return {
    uploadImage,
    changeBackground,
    downloadImage
  }
} 